package com.chart.web.controller.chart.sta;

import com.chart.common.core.domain.AjaxResult;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("/baidu")
public class BaiduPushController {
    private static final String PUSH_URL = "http://data.zz.baidu.com/urls";

    @GetMapping("/pushUrls")
    public AjaxResult pushUrls() {
        try {
            // 将site, token, 和 urls 写死在代码中
            String site = "https://topcharts.cn";
            String token = "81lUiIXJEKHuahfu";
            String[] urls = new String[]{
                    "https://topcharts.cn"
            };

            // 构建推送URL
            String requestUrl = String.format("%s?site=%s&token=%s", PUSH_URL, site, token);

            // 创建 HTTP 请求
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            HttpEntity<String> request = new HttpEntity<>(String.join("\n", urls), headers);

            Map baiduResponse = restTemplate.postForObject(requestUrl, request, Map.class);
            return AjaxResult.success(baiduResponse);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
